<?php
// +----------------------------------------------------------------------
// | 食得鲜API [ shidexian ] 外露数据 [ 上鲜送 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.shidexian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 何锐 <poptser@foxmail.com>  [ ON THE WAY ]
// +----------------------------------------------------------------------
// | DateTime：2017年4月10日17:36:02
// +----------------------------------------------------------------------
namespace SDXApi\Controller;
use Think\Controller;
use Think\Model;
class DownController extends Controller {
    public function _initialize(){

    }
    public function index(){
        /*$admin_user=M('Admin_user');
        $data=$admin_user->select();
        dump($data);*/;
        $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px } a,a:hover{color:blue;}</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>食得鲜 数据平台</b>！</p></div>','utf-8');
        // dump(get_lng_lat('猎德大道46号尚东美御d1102'));

    }

    /**
     * 显示生鲜送相关账号下的送达信息  包含 未送达 和 已送达
     */
    public function show_cc(){

        if(IS_POST){
            $start_date = I("post.start_date");
            $end_date = I("post.end_date");
            session("start_date",$start_date);
            session("end_date",$end_date);
            $show = I("post.show");
        }else{
            if(session("start_date")){
                $start_date = session("start_date");
                $end_date = session("end_date");
                $show = I("get.show");
            }else{
                $start_date = date("Y-m-d",time());
                $end_date = date("Y-m-d",time());
                session("start_date",$start_date);
                session("end_date",$end_date);
                $show = I("get.show");
            }
        }

        $this->assign("start_date",$start_date);
        $this->assign("end_date",$end_date);

        if(empty($show)){
            $show = "ing";
        }
        if($show=="complete"){
            //完成订单
            $where= "o.shipping_status =2 and o.pay_status in (2,3) and 
            o.order_status <>2  and o.shipping_id = 3 and 
            o.wdr_id = wdr.id and wdr.wdtype in (6,7,16,17,20,21,22,23) and o.order_id = oa.order_id and
            oa.action_user like '%谭耀辉-出仓%' 
            and TO_DAYS(from_unixtime(o.best_time)) >= TO_DAYS('$start_date') and
             TO_DAYS(from_unixtime(o.best_time)) <= TO_DAYS('$end_date')";
            $this->assign("show",'ing');
            $this->assign("show1",'refund');
            $this->assign("down",'complete');

        }elseif($show=="ing"){
            //进行中订单
            $where= "o.shipping_status !=2 and o.pay_status in (2,3) and 
            o.order_status <>2  and o.shipping_id = 3 and
            o.wdr_id = wdr.id and wdr.wdtype not in (6,7,13,14,16,17,20,21,22) and o.order_id = oa.order_id and
            oa.action_user not like '%谭耀辉-出仓%' 
            and TO_DAYS(from_unixtime(o.best_time)) >= TO_DAYS('$start_date') and
             TO_DAYS(from_unixtime(o.best_time)) <= TO_DAYS('$end_date')";
            $this->assign("show",'complete');
            $this->assign("show1",'refund');
            $this->assign("down",'ing');
        }else{
            //全部退款
            $where= "o.pay_status = 4 and o.shipping_id = 3 and 
            o.wdr_id = wdr.id and wdr.wdtype in (6,7,16,17,20,21,22,23) and o.order_id = oa.order_id and
            oa.action_user like '%谭耀辉-出仓%' 
            and TO_DAYS(from_unixtime(o.best_time)) >= TO_DAYS('$start_date') and
             TO_DAYS(from_unixtime(o.best_time)) <= TO_DAYS('$end_date')";
            $this->assign("show",'ing');
            $this->assign("show1",'complete');
            $this->assign("down",'refund');
        }
        $distribution_cost_all =0;
        $normal_cost_all =0;
        $late_cost_all =0;
        //$order_info = M()->table(array('sdx_order_info'=>'o','sdx_warehouse_deliver_region'=>'wdr','sdx_order_action'=>'oa'))
        //    ->where($where)->field("o.*,wdr.name,wdr.first_heavy,wdr.continued_heavy")->group('order_id')->order('best_time_start')->select();
        //dump(M()->getlastsql());
        $order_info = M()->query("SELECT o.*,
       wdr.name,
       wdr.first_heavy,
       wdr.continued_heavy
  FROM `sdx_order_info` `o`,
       `sdx_warehouse_deliver_region` `wdr`
 WHERE(o.shipping_status!= 2
   and o.pay_status in(2, 3)
   and o.order_status<> 2
   and o.shipping_id= 3
   and o.wdr_id= wdr.id
   and o.is_presell = 1 AND o.buckle_inventory=0
   and TO_DAYS(from_unixtime(o.best_time))>= TO_DAYS('2017-05-07')
   and TO_DAYS(from_unixtime(o.best_time))<= TO_DAYS('2017-05-07'))
 GROUP BY order_id
 ORDER BY best_time_start");
        foreach ($order_info as $key=>$value){
            $goods_info = A("Autoserver")->get_goods_list_real($value['order_id'],false,"name");
            $order_info[$key]['goods_name'] = str_replace("\n","<br/>",$goods_info['goods_name']);
            $order_info[$key]['goods_weight'] = $goods_info['goods_weight'];
            $order_info[$key]['goods_num'] = $goods_info['goods_num'];
            $order_info[$key]['address'] = A("Autoserver")->get_address_desc($value['province'], $value['city'], $value['district']).$value['address'].$value['address_name'];
            $order_info[$key]['best_time'] = date("Y-m-d H:i:s",$value['best_time']);
            $order_info[$key]['best_time_start'] = date("Y-m-d H:i:s",$value['best_time_start']);
            $goods_weight = ceil($goods_info['goods_weight']);  //商品重量
            if($goods_weight>3){
                //首重费用和续重费用
                $goods_weight_ext = $goods_weight-3;
                $order_info[$key]['distribution_cost'] = $value['first_heavy']+$value['continued_heavy']*$goods_weight_ext;
            }else{
                //仅首重费用
                $order_info[$key]['distribution_cost'] = $value['first_heavy'];

            }
            if($value['shipping_status']==2){
                $order_info[$key]['delayed_time'] = round(($value['confirm_time'] - $value['best_time'] + 28800)/3600,1);
                if ($order_info[$key]['delayed_time']<=0){
                    $order_info[$key]['delayed_time'] = "准时";
                    $normal_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "normal";
                }else{
                    $late_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "late";
                }
            }else{
                $order_info[$key]['delayed_time'] = round(($value['best_time']-time())/3600,1);
                if ($order_info[$key]['delayed_time']<=0){
                    $order_info[$key]['delayed_time'] = "已超时";
                    $late_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "late";
                }else{
                    $normal_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "normal";
                }
            }
            $distribution_cost_all += $order_info[$key]['distribution_cost'];
        }
        $this->assign("distribution_cost_all",$distribution_cost_all);
        $this->assign("normal_cost_all",$normal_cost_all);
        $this->assign("late_cost_all",$late_cost_all);
        //dump($order_info);
        if(I("get.type")=="down"){
            //下载
            import('Vendor.PHPExcel.PHPExcel');
            import('Vendor.PHPExcel.PHPExcel.Reader.Excel5');
            import('Vendor.PHPExcel.PHPExcel.IOFactory');
            $objPHPExcel = new \PHPExcel();
            $objPHPExcel->getProperties()->setCreator("shidexian@youguoshu")
                ->setLastModifiedBy("shidexian@youguoshu")
                ->setTitle("download file shidexian@youguoshu")
                ->setSubject("shidexian@youguoshu")
                ->setDescription("shidexian@youguoshu")
                ->setKeywords("shidexian")
                ->setCategory("shidexian");

            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(5);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(60);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(40);
            $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getStyle('A1:N1')->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle( 'A1:N1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle( 'A1:N1')->getFill()->getStartColor()->setARGB('FF039BE5');

            $objPHPExcel->getActiveSheet()->getStyle('A:N')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);

            $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                    ),
                ),
            );

            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue('A1','订单编号')
                ->setCellValue('B1','产品名称')
                ->setCellValue('C1','规格(kg)')
                ->setCellValue('D1','数量')
                ->setCellValue('E1','运费')
                ->setCellValue('F1','客人姓名')
                ->setCellValue('G1','电话')
                ->setCellValue('H1','区域')
                ->setCellValue('I1','地址')
                ->setCellValue('J1','标志性建筑')
                ->setCellValue('K1','送达时间范围')
                ->setCellValue('L1','状态')
                ->setCellValue('M1','迟到送达时间')
                ->setCellValue('N1','备注');
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
            $objPHPExcel->getActiveSheet()->getStyle('A1:N1')->applyFromArray($styleArray);

            foreach ($order_info as $k => $v) {
                switch ($v['shipping_status']){
                    case 1:
                        $shipping_status = "已发货";
                        break;
                    case 2:
                        $shipping_status = "收货确认";
                        break;
                    case 5:
                        $shipping_status = "发货中";
                        break;
                    default:
                        $shipping_status = "未知";
                }
                $num = $k + 2;
                $objPHPExcel->getActiveSheet()->getRowDimension($num)->setRowHeight(30);
                $objPHPExcel->getActiveSheet()->getStyle('A'.$num.':N'.$num)->applyFromArray($styleArray);
                $objPHPExcel->getActiveSheet()->getStyle('B'.$num)->getAlignment()->setWrapText(true);
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValueExplicit('A' . $num, $v['order_sn'],\PHPExcel_Cell_DataType::TYPE_STRING)
                    ->setCellValue('B' . $num, str_replace("<br/>","\n",$v['goods_name']))
                    ->setCellValueExplicit('C' . $num, $v['goods_weight'],\PHPExcel_Cell_DataType::TYPE_STRING)
                    ->setCellValue('D' . $num, $v['goods_num'])
                    ->setCellValue('E' . $num, $v['distribution_cost'])
                    ->setCellValue('F' . $num, $v['consignee'])
                    ->setCellValue('G' . $num, $v['mobile'])
                    ->setCellValue('H' . $num, $v['name'])
                    ->setCellValue('I' . $num, $v['address'])
                    ->setCellValue('J' . $num, $v['sign_building'])
                    ->setCellValue('K' . $num, $v['best_time_start']."-".$v['best_time'])
                    ->setCellValue('L' . $num, $shipping_status)
                    ->setCellValue('M' . $num, $v['delayed_time'])
                    ->setCellValue('N' . $num, $v['postscript']);
            }
            $line_num = $num+1;
            $objPHPExcel->getActiveSheet()->mergeCells('A'.$line_num.':N'.$line_num);
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$line_num, "食得鲜订单信息");
            $objPHPExcel->getActiveSheet()->getStyle('A'.$line_num)->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->setTitle('User');
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="shidexian.xls"');
            header('Cache-Control: max-age=0');
            $write = new \PHPExcel_Writer_Excel5($objPHPExcel);
            $write->save('php://output');
            exit;
        }else{
            $this->assign("order_info",$order_info);
            $this->display();
        }

    }
    /**
     *异步查询订单操作信息和基础信息
     */
    public function notify_select($order_sn){
        if (empty($order_sn)) return false;
        $sql = "SELECT sdx_order_action.* FROM  sdx_order_action,sdx_order_info WHERE sdx_order_info.order_id = sdx_order_action.order_id and sdx_order_info.order_sn = '".$order_sn."'";
        $data_s = M()->query($sql);
        foreach ($data_s as $kk=>$vv){

            $data_s[$kk]['log_time'] = local_date('Y-m-d H:i:s',$vv['log_time']);

            switch ($vv['order_status']){
                case 0:
                    $data_s[$kk]['order_status'] = "未确认";
                    break;
                case 1:
                    $data_s[$kk]['order_status'] = "已确认";
                    break;
                case 2:
                    $data_s[$kk]['order_status'] = "已取消";
                    break;
                case 3:
                    $data_s[$kk]['order_status'] = "无效";
                    break;
                case 4:
                    $data_s[$kk]['order_status'] = "退货";
                    break;
                case 5:
                    $data_s[$kk]['order_status'] = "已发货";
                    break;
            }

            switch ($vv['shipping_status']){
                case 0:
                    $data_s[$kk]['shipping_status'] = "未发货";
                    break;
                case 1:
                    $data_s[$kk]['shipping_status'] = "已发货";
                    break;
                case 2:
                    $data_s[$kk]['shipping_status'] = "已收货";
                    break;
                case 3:
                    $data_s[$kk]['shipping_status'] = "备货中";
                    break;
                case 4:
                    $data_s[$kk]['shipping_status'] = "备货中";
                    break;
                case 5:
                    $data_s[$kk]['shipping_status'] = "已备货";
                    break;
                case 7:
                    $data_s[$kk]['shipping_status'] = "--";
                    break;
            }


            switch ($vv['pay_status']){
                case 0:
                    $data_s[$kk]['pay_status'] = "未付款";
                    break;
                case 1:
                    $data_s[$kk]['pay_status'] = "付款中";
                    break;
                case 2:
                    $data_s[$kk]['pay_status'] = "已付款";
                    break;
                case 3:
                    $data_s[$kk]['pay_status'] = "部分退款";
                    break;
                case 4:
                    $data_s[$kk]['pay_status'] = "全部退款";
                    break;
            }
        }

        $data['order_action'] = $data_s;

        $sql_order_info = "SELECT consignee,province,city,district,address,mobile,best_time,best_time_start,shipping_id,sign_building FROM  sdx_order_info WHERE order_sn = '".$order_sn."'";
        $data_order_info = M()->query($sql_order_info);

        $data_order_info = $data_order_info[0];

        $data['username'] = $data_order_info['consignee'];
        $data['userphone'] = $data_order_info['mobile'];
        $data['address'] = $data_order_info['sign_building']."(".$data_order_info['address'].")";
        $data['best_time'] = $data_order_info['best_time'];
        $data['best_time_start'] = $data_order_info['best_time_start'];



        if ($data['best_time'] == 0) {
            $data['best_time_2'] = "无期望时间";
        } else {


            if ($data['best_time_start']) {
                $data['best_time_2'] = date('Y-m-d H:i:s', $data['best_time_start']) . "-" . date('Y-m-d H:i:s', $data['best_time']);
            } else {
                if ($data['is_presell'] == 1) {
                    //预售单
                    $order['best_time_2'] = date('Y-m-d' . " 10:00:00", $data['best_time']) . "  -   " . date('Y-m-d' . " 20:30:00", $data['best_time']);
                } else {
                    if ($data['shipping_id'] == 2) {
                        //自提订单
                        $order['best_time_2'] = date('Y-m-d' . " 10:00:00", $data['best_time']) . "  -   " . date('Y-m-d' . " 20:30:00", $data['best_time']);
                    } else {
                        $order['best_time_2'] = date('Y-m-d H:i:s', $data['best_time'] - 7199) . "  -   " . date('Y-m-d H:i:s', $data['best_time'] + 1);
                    }
                }
            }
        }

        echo json_encode($data);
    }
}